package ltd.dujiabao.eduservice.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.commonutils.Result;
import ltd.dujiabao.eduservice.entity.EduChapter;
import ltd.dujiabao.eduservice.entity.chapter.ChapterVo;
import ltd.dujiabao.eduservice.service.EduChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author dujiabao
 * @since 2021-04-21
 */
@Api(value = "章节")
@CrossOrigin
@RestController
@RequestMapping("/eduservice/chapter")
@Slf4j
public class EduChapterController {
  @Autowired
  EduChapterService eduChapterService;

  @ApiOperation("查询章节及小节")
  @GetMapping("/tree/{courseId}")
  public Result getChapterVideoTree(@ApiParam(name = "courseId", value = "课程id", required = true) @PathVariable String courseId) {
    Collection<ChapterVo> tree = eduChapterService.getChapterVideoTree(courseId);
    log.info("查询章节及小节，结果：" + tree.toString());
    return Result.success().addData("data", tree);
  }

  @ApiOperation("添加章节")
  @PostMapping("/")
  public Result addChapter(@ApiParam(name = "eduChapter", value = "章节信息", required = true) @RequestBody EduChapter eduChapter) {
    boolean isSuccess = eduChapterService.save(eduChapter);
    if (isSuccess) {
      log.info("添加章节成功：" + eduChapter.toString());
      return Result.success();
    } else {
      log.error("添加章节失败：" + eduChapter.toString());
      return Result.failure();
    }
  }

  @ApiOperation("获取章节")
  @GetMapping("/{id}")
  public Result getChapter(@ApiParam(name = "id", value = "章节id", required = true) @PathVariable String id) {
    EduChapter chapter = eduChapterService.getById(id);
    log.info("获取章节，结果：" + chapter.toString());
    return Result.success().addData("data", chapter);
  }

  @ApiOperation("删除章节")
  @DeleteMapping("/{id}")
  public Result removeChapter(@ApiParam(name = "id", value = "章节id", required = true) @PathVariable String id) {
    boolean isSuccess = eduChapterService.removeChapter(id);
    if (isSuccess) {
      log.info("删除" + id + "章节成功");
      return Result.success();
    } else {
      log.error("删除" + id + "章节失败");
      return Result.failure();
    }
  }

  @ApiOperation("修改章节")
  @PutMapping("/{id}")
  public Result updateChapter(@ApiParam(name = "id", value = "章节id", required = true) @PathVariable String id,
                              @ApiParam(name = "eduChapter", value = "章节信息", required = true) @RequestBody EduChapter eduChapter) {
    eduChapter.setId(id);
    boolean isSuccess = eduChapterService.updateById(eduChapter);
    if (isSuccess) {
      log.info("更新" + id + "章节成功：" + eduChapter.toString());
      return Result.success();
    } else {
      log.error("更新" + id + "章节失败：" + eduChapter.toString());
      return Result.failure();
    }
  }
}

